package com.prince.web.base;

import com.prince.constant.Constants;
import com.prince.model.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionUtil {
    /**
     * 功能描述: 获取session中的用户
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/8 11:21
     */
    public static User getSession(){
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        Object user = request.getSession().getAttribute(Constants.USER);
        if(null == user){
            return null;
        }
        return (User)user;
    }
    /**
     * 功能描述: session中添加数据
     * @Author: 王培喜 58528792@163.com
     * @Date: 2021/4/8 11:21
     */
    public static void setSession(User user){
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        user.setRemark(session.getId());
        session.setAttribute(Constants.USER,user);
    }

    public static void invalidate(){
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        HttpSession session = request.getSession();
        session.invalidate();
    }

}
